﻿using System.Collections.Generic;
using System.Linq;

namespace KamLib
{
    public class EquipInterfaceContainer
    {
        private List<object> list;

        public EquipInterfaceContainer Register(object item)
        {
            if (list == null) list = new List<object>();
            if (!list.Contains(item))
            {
                list.Add(item);
                if (item is IEquipContainer)
                    ((IEquipContainer)item).Owner = this;
            }
            return this;
        }

        public T Register<T>(T item) where T: class
        {
            Register((object)item);
            return item;
        }

        public T Get<T>() where T : IEquipContainer
        {
            return list != null ? list.OfType<T>().FirstOrDefault() : default(T);
        }
    }

    public interface IEquipContainer
    {
        EquipInterfaceContainer Owner { get; set; }
    }

    public class EquipContainer : IEquipContainer
    {
        private EquipInterfaceContainer _owner;
        public EquipInterfaceContainer Owner
        {
            get { return _owner ?? (_owner = new EquipInterfaceContainer().Register((object)this)); }
            set { _owner = value; }
        }

        public T Get<T>() where T : IEquipContainer
        {
            return _owner!=null ? _owner.Get<T>() : default(T);
        }
    }
}